package daa.levelup.aCipher;

/**
 * Created by Capper on 15.02.14.
 */
public class aCaeasar implements ICipher{
    String alphabet;


    public aCaeasar(String _alphabet){
        alphabet=_alphabet;
    }

    @Override
    public String getEncryption(String text, String key_str){
        int position = hash_key( key_str);
        String cipher ="";
        for(int i=0;i<text.length();i++){
            cipher+=alphabet.charAt((alphabet.indexOf(text.charAt(i))+position)%alphabet.length());
        }
        return cipher;
    }

    private int hash_key( String str){
        int res = 0;
        for (int i=0;i<str.length();i++){
            res += alphabet.indexOf(str.charAt(i));
        }
        return res;
    }


    @Override
    public String getDecryption(String cipher, String key_str){
        int position = hash_key( key_str);
        String text ="";
        for(int i=0;i<cipher.length();i++){
            if(alphabet.indexOf(cipher.charAt(i))-position<0){
                text+=alphabet.charAt(alphabet.length() - 1 +
                        (alphabet.indexOf(cipher.charAt(i))-position + 1)%alphabet.length());
            }else{
                text+=alphabet.charAt((alphabet.indexOf(cipher.charAt(i))-position)%alphabet.length());
            }
        }
        return text;
    }

}
